#!/bin/bash
# fastlinux_v0.5 - Linux系统自动化安装和配置脚本
# 代码由ZJY编写

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # 无颜色

# 全局变量
DISTRO=""
RELEASE=""
CODENAME=""
HAS_DESKTOP=false

# 捕获Ctrl+C信号
trap 'echo -e "\n${RED}用户中断操作，程序退出${NC}"; exit 1' SIGINT

# 显示用户须知
show_user_agreement() {
    clear
    echo -e "${BLUE}=============================================${NC}"
    echo -e "${CYAN}               用户须知                       ${NC}"
    echo -e "${BLUE}=============================================${NC}"
    echo -e "1. 本代码由ZJY编写"
    echo -e "2. 本脚本仅供个人学习使用，不得商用"
    echo -e "3. 使用前请检查代码，了解脚本执行的操作"
    echo -e "4. 执行本脚本可能需要管理员权限，部分操作会修改系统配置"
    echo -e "5. 建议在新安装的系统上使用，避免与现有配置冲突"
    echo -e "\n${YELLOW}请仔细阅读以上条款${NC}"
    read -p "是否同意以上条款？(y/n): " agree
    if [ "$agree" != "y" ] && [ "$agree" != "Y" ]; then
        echo -e "${RED}您不同意用户须知，程序将退出${NC}"
        exit 0
    fi
}

# 系统检测
detect_system() {
    echo -e "${BLUE}正在检测系统信息...${NC}"
    
    # 检测发行版
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        DISTRO=$ID
        RELEASE=$VERSION_ID
        CODENAME=$VERSION_CODENAME
    elif [ -f /etc/redhat-release ]; then
        if grep -qi "centos" /etc/redhat-release; then
            DISTRO="centos"
        elif grep -qi "redhat" /etc/redhat-release; then
            DISTRO="rhel"
        fi
        RELEASE=$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release | head -1)
    else
        echo -e "${RED}无法检测到操作系统类型${NC}"
        handle_error "系统检测失败"
        return 1
    fi

    # 检测是否有桌面环境
    if [ -n "$DISPLAY" ] || [ -n "$XDG_SESSION_TYPE" ] || pgrep -x "Xorg" > /dev/null; then
        HAS_DESKTOP=true
        echo -e "${GREEN}检测到桌面环境${NC}"
    else
        HAS_DESKTOP=false
        echo -e "${YELLOW}未检测到桌面环境，将在后续步骤中安装${NC}"
    fi

    echo -e "${GREEN}系统检测完成: $DISTRO $RELEASE $CODENAME${NC}"
    return 0
}

# 错误处理函数
handle_error() {
    local message=$1
    echo -e "${RED}错误: $message${NC}"
    read -p "请选择 (1) 重试 (2) 跳过: " choice
    case $choice in
        1) return 1 ;;  # 重试
        2) return 0 ;;  # 跳过
        *) 
            echo -e "${YELLOW}无效选择，默认跳过${NC}"
            return 0 
            ;;
    esac
}

# 源管理主菜单
source_menu() {
    while true; do
        clear
        echo -e "${BLUE}=============================================${NC}"
        echo -e "${CYAN}               源管理菜单                     ${NC}"
        echo -e "${BLUE}=============================================${NC}"
        echo -e "当前系统: ${YELLOW}$DISTRO $RELEASE${NC}"
        echo -e "1. 切换到清华源"
        echo -e "2. 切换到阿里云源"
        echo -e "3. 切换到中科大源"
        echo -e "4. 切换到官方源"
        echo -e "5. 备份当前源配置"
        echo -e "6. 恢复源配置"
        echo -e "0. 返回主菜单"
        echo -e "${BLUE}=============================================${NC}"
        read -p "请选择操作 [0-6]: " choice

        case $choice in
            1) change_to_tsinghua && wait_for_enter ;;
            2) change_to_aliyun && wait_for_enter ;;
            3) change_to_ustc && wait_for_enter ;;
            4) change_to_official && wait_for_enter ;;
            5) backup_sources && wait_for_enter ;;
            6) restore_sources && wait_for_enter ;;
            0) break ;;
            *) 
                echo -e "${RED}无效选择，请重试${NC}"
                wait_for_enter
                ;;
        esac
    done
}

# 备份源配置
backup_sources() {
    echo -e "${BLUE}正在备份源配置...${NC}"
    
    local backup_dir="$HOME/fastlinux_backups/sources"
    mkdir -p "$backup_dir"
    local timestamp=$(date +%Y%m%d_%H%M%S)
    
    if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
        if [ -f /etc/apt/sources.list ]; then
            cp /etc/apt/sources.list "$backup_dir/sources.list.$timestamp" && \
            echo -e "${GREEN}源配置已备份到 $backup_dir/sources.list.$timestamp${NC}" && return 0
        fi
    elif [[ $DISTRO == "centos" || $DISTRO == "rhel" || $DISTRO == "fedora" ]]; then
        if [ -d /etc/yum.repos.d/ ]; then
            cp -r /etc/yum.repos.d/ "$backup_dir/yum.repos.d.$timestamp" && \
            echo -e "${GREEN}源配置已备份到 $backup_dir/yum.repos.d.$timestamp${NC}" && return 0
        fi
    fi
    
    echo -e "${RED}备份源配置失败${NC}"
    return 1
}

# 恢复源配置
restore_sources() {
    echo -e "${BLUE}正在恢复源配置...${NC}"
    
    local backup_dir="$HOME/fastlinux_backups/sources"
    if [ ! -d "$backup_dir" ]; then
        echo -e "${RED}没有找到备份文件${NC}"
        return 1
    fi
    
    echo -e "${YELLOW}可用的备份:${NC}"
    ls -1 "$backup_dir" | grep -v '^$'
    
    read -p "请输入要恢复的备份文件名: " backup_file
    local full_path="$backup_dir/$backup_file"
    
    if [ ! -e "$full_path" ]; then
        echo -e "${RED}备份文件不存在${NC}"
        return 1
    fi
    
    if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
        if [[ $backup_file == sources.list.* ]]; then
            sudo cp "$full_path" /etc/apt/sources.list && \
            echo -e "${GREEN}源配置已恢复${NC}" && return 0
        else
            echo -e "${RED}无效的备份文件类型${NC}"
            return 1
        fi
    elif [[ $DISTRO == "centos" || $DISTRO == "rhel" || $DISTRO == "fedora" ]]; then
        if [[ $backup_file == yum.repos.d.* ]]; then
            sudo rm -rf /etc/yum.repos.d/*
            sudo cp -r "$full_path"/* /etc/yum.repos.d/ && \
            echo -e "${GREEN}源配置已恢复${NC}" && return 0
        else
            echo -e "${RED}无效的备份文件类型${NC}"
            return 1
        fi
    fi
    
    return 1
}

# 切换到清华源
change_to_tsinghua() {
    echo -e "${BLUE}正在切换到清华源...${NC}"
    
    # 先备份当前源
    backup_sources || return 1
    
    if [[ $DISTRO == "ubuntu" ]]; then
        if [ -z "$CODENAME" ]; then
            echo -e "${RED}无法确定Ubuntu版本代号${NC}"
            return 1
        fi
        
        sudo tee /etc/apt/sources.list << EOF
# 清华源 Ubuntu $RELEASE ($CODENAME)
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ $CODENAME main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ $CODENAME-updates main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ $CODENAME-backports main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ $CODENAME-security main restricted universe multiverse
EOF
        sudo apt update && echo -e "${GREEN}已切换到清华源${NC}" && return 0
        
    elif [[ $DISTRO == "debian" ]]; then
        if [ -z "$CODENAME" ]; then
            echo -e "${RED}无法确定Debian版本代号${NC}"
            return 1
        fi
        
        sudo tee /etc/apt/sources.list << EOF
# 清华源 Debian $RELEASE ($CODENAME)
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ $CODENAME main contrib non-free
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ $CODENAME-updates main contrib non-free
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ $CODENAME-backports main contrib non-free
deb https://mirrors.tuna.tsinghua.edu.cn/debian-security/ $CODENAME-security main contrib non-free
EOF
        sudo apt update && echo -e "${GREEN}已切换到清华源${NC}" && return 0
        
    elif [[ $DISTRO == "centos" ]]; then
        sudo tee /etc/yum.repos.d/CentOS-Base.repo << EOF
[base]
name=CentOS-\$releasever - Base - 清华源
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/\$releasever/os/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[updates]
name=CentOS-\$releasever - Updates - 清华源
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/\$releasever/updates/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[extras]
name=CentOS-\$releasever - Extras - 清华源
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/\$releasever/extras/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever
EOF
        sudo yum clean all && sudo yum makecache && echo -e "${GREEN}已切换到清华源${NC}" && return 0
        
    elif [[ $DISTRO == "fedora" ]]; then
        sudo tee /etc/yum.repos.d/fedora.repo << EOF
[fedora]
name=Fedora \$releasever - \$basearch - 清华源
baseurl=https://mirrors.tuna.tsinghua.edu.cn/fedora/releases/\$releasever/Everything/\$basearch/os/
enabled=1
metadata_expire=28d
gpgcheck=1
gpgkey=https://mirrors.tuna.tsinghua.edu.cn/fedora/releases/\$releasever/Everything/\$basearch/os/RPM-GPG-KEY-fedora-\$releasever-\$basearch

[updates]
name=Fedora \$releasever - \$basearch - Updates - 清华源
baseurl=https://mirrors.tuna.tsinghua.edu.cn/fedora/updates/\$releasever/\$basearch/
enabled=1
metadata_expire=6h
gpgcheck=1
gpgkey=https://mirrors.tuna.tsinghua.edu.cn/fedora/updates/\$releasever/\$basearch/RPM-GPG-KEY-fedora-\$releasever-\$basearch
EOF
        sudo dnf clean all && sudo dnf makecache && echo -e "${GREEN}已切换到清华源${NC}" && return 0
        
    elif [[ $DISTRO == "rhel" ]]; then
        echo -e "${YELLOW}Red Hat Enterprise Linux 建议使用订阅源，不推荐替换${NC}"
        return 1
    fi
    
    echo -e "${RED}切换到清华源失败${NC}"
    return 1
}

# 切换到阿里云源
change_to_aliyun() {
    echo -e "${BLUE}正在切换到阿里云源...${NC}"
    
    # 先备份当前源
    backup_sources || return 1
    
    if [[ $DISTRO == "ubuntu" ]]; then
        if [ -z "$CODENAME" ]; then
            echo -e "${RED}无法确定Ubuntu版本代号${NC}"
            return 1
        fi
        
        sudo tee /etc/apt/sources.list << EOF
# 阿里云源 Ubuntu $RELEASE ($CODENAME)
deb http://mirrors.aliyun.com/ubuntu/ $CODENAME main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ $CODENAME-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ $CODENAME-backports main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ $CODENAME-security main restricted universe multiverse
EOF
        sudo apt update && echo -e "${GREEN}已切换到阿里云源${NC}" && return 0
        
    elif [[ $DISTRO == "debian" ]]; then
        if [ -z "$CODENAME" ]; then
            echo -e "${RED}无法确定Debian版本代号${NC}"
            return 1
        fi
        
        sudo tee /etc/apt/sources.list << EOF
# 阿里云源 Debian $RELEASE ($CODENAME)
deb http://mirrors.aliyun.com/debian/ $CODENAME main contrib non-free
deb http://mirrors.aliyun.com/debian/ $CODENAME-updates main contrib non-free
deb http://mirrors.aliyun.com/debian/ $CODENAME-backports main contrib non-free
deb http://mirrors.aliyun.com/debian-security/ $CODENAME-security main contrib non-free
EOF
        sudo apt update && echo -e "${GREEN}已切换到阿里云源${NC}" && return 0
        
    elif [[ $DISTRO == "centos" ]]; then
        sudo tee /etc/yum.repos.d/CentOS-Base.repo << EOF
[base]
name=CentOS-\$releasever - Base - 阿里云
baseurl=http://mirrors.aliyun.com/centos/\$releasever/os/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[updates]
name=CentOS-\$releasever - Updates - 阿里云
baseurl=http://mirrors.aliyun.com/centos/\$releasever/updates/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[extras]
name=CentOS-\$releasever - Extras - 阿里云
baseurl=http://mirrors.aliyun.com/centos/\$releasever/extras/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever
EOF
        sudo yum clean all && sudo yum makecache && echo -e "${GREEN}已切换到阿里云源${NC}" && return 0
        
    elif [[ $DISTRO == "fedora" ]]; then
        sudo tee /etc/yum.repos.d/fedora.repo << EOF
[fedora]
name=Fedora \$releasever - \$basearch - 阿里云
baseurl=http://mirrors.aliyun.com/fedora/releases/\$releasever/Everything/\$basearch/os/
enabled=1
metadata_expire=28d
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/fedora/releases/\$releasever/Everything/\$basearch/os/RPM-GPG-KEY-fedora-\$releasever-\$basearch

[updates]
name=Fedora \$releasever - \$basearch - Updates - 阿里云
baseurl=http://mirrors.aliyun.com/fedora/updates/\$releasever/\$basearch/
enabled=1
metadata_expire=6h
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/fedora/updates/\$releasever/\$basearch/RPM-GPG-KEY-fedora-\$releasever-\$basearch
EOF
        sudo dnf clean all && sudo dnf makecache && echo -e "${GREEN}已切换到阿里云源${NC}" && return 0
        
    elif [[ $DISTRO == "rhel" ]]; then
        echo -e "${YELLOW}Red Hat Enterprise Linux 建议使用订阅源，不推荐替换${NC}"
        return 1
    fi
    
    echo -e "${RED}切换到阿里云源失败${NC}"
    return 1
}

# 切换到中科大源
change_to_ustc() {
    echo -e "${BLUE}正在切换到中科大源...${NC}"
    
    # 先备份当前源
    backup_sources || return 1
    
    if [[ $DISTRO == "ubuntu" ]]; then
        if [ -z "$CODENAME" ]; then
            echo -e "${RED}无法确定Ubuntu版本代号${NC}"
            return 1
        fi
        
        sudo tee /etc/apt/sources.list << EOF
# 中科大源 Ubuntu $RELEASE ($CODENAME)
deb https://mirrors.ustc.edu.cn/ubuntu/ $CODENAME main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ $CODENAME-updates main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ $CODENAME-backports main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ $CODENAME-security main restricted universe multiverse
EOF
        sudo apt update && echo -e "${GREEN}已切换到中科大源${NC}" && return 0
        
    elif [[ $DISTRO == "debian" ]]; then
        if [ -z "$CODENAME" ]; then
            echo -e "${RED}无法确定Debian版本代号${NC}"
            return 1
        fi
        
        sudo tee /etc/apt/sources.list << EOF
# 中科大源 Debian $RELEASE ($CODENAME)
deb https://mirrors.ustc.edu.cn/debian/ $CODENAME main contrib non-free
deb https://mirrors.ustc.edu.cn/debian/ $CODENAME-updates main contrib non-free
deb https://mirrors.ustc.edu.cn/debian/ $CODENAME-backports main contrib non-free
deb https://mirrors.ustc.edu.cn/debian-security/ $CODENAME-security main contrib non-free
EOF
        sudo apt update && echo -e "${GREEN}已切换到中科大源${NC}" && return 0
        
    elif [[ $DISTRO == "centos" ]]; then
        sudo tee /etc/yum.repos.d/CentOS-Base.repo << EOF
[base]
name=CentOS-\$releasever - Base - 中科大
baseurl=https://mirrors.ustc.edu.cn/centos/\$releasever/os/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[updates]
name=CentOS-\$releasever - Updates - 中科大
baseurl=https://mirrors.ustc.edu.cn/centos/\$releasever/updates/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[extras]
name=CentOS-\$releasever - Extras - 中科大
baseurl=https://mirrors.ustc.edu.cn/centos/\$releasever/extras/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever
EOF
        sudo yum clean all && sudo yum makecache && echo -e "${GREEN}已切换到中科大源${NC}" && return 0
        
    elif [[ $DISTRO == "fedora" ]]; then
        sudo tee /etc/yum.repos.d/fedora.repo << EOF
[fedora]
name=Fedora \$releasever - \$basearch - 中科大
baseurl=https://mirrors.ustc.edu.cn/fedora/releases/\$releasever/Everything/\$basearch/os/
enabled=1
metadata_expire=28d
gpgcheck=1
gpgkey=https://mirrors.ustc.edu.cn/fedora/releases/\$releasever/Everything/\$basearch/os/RPM-GPG-KEY-fedora-\$releasever-\$basearch

[updates]
name=Fedora \$releasever - \$basearch - Updates - 中科大
baseurl=https://mirrors.ustc.edu.cn/fedora/updates/\$releasever/\$basearch/
enabled=1
metadata_expire=6h
gpgcheck=1
gpgkey=https://mirrors.ustc.edu.cn/fedora/updates/\$releasever/\$basearch/RPM-GPG-KEY-fedora-\$releasever-\$basearch
EOF
        sudo dnf clean all && sudo dnf makecache && echo -e "${GREEN}已切换到中科大源${NC}" && return 0
        
    elif [[ $DISTRO == "rhel" ]]; then
        echo -e "${YELLOW}Red Hat Enterprise Linux 建议使用订阅源，不推荐替换${NC}"
        return 1
    fi
    
    echo -e "${RED}切换到中科大源失败${NC}"
    return 1
}

# 切换到官方源
change_to_official() {
    echo -e "${BLUE}正在切换到官方源...${NC}"
    
    # 先备份当前源
    backup_sources || return 1
    
    if [[ $DISTRO == "ubuntu" ]]; then
        if [ -z "$CODENAME" ]; then
            echo -e "${RED}无法确定Ubuntu版本代号${NC}"
            return 1
        fi
        
        sudo tee /etc/apt/sources.list << EOF
# Ubuntu 官方源 $RELEASE ($CODENAME)
deb http://archive.ubuntu.com/ubuntu/ $CODENAME main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu/ $CODENAME-updates main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu/ $CODENAME-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu/ $CODENAME-security main restricted universe multiverse
EOF
        sudo apt update && echo -e "${GREEN}已切换到官方源${NC}" && return 0
        
    elif [[ $DISTRO == "debian" ]]; then
        if [ -z "$CODENAME" ]; then
            echo -e "${RED}无法确定Debian版本代号${NC}"
            return 1
        fi
        
        sudo tee /etc/apt/sources.list << EOF
# Debian 官方源 $RELEASE ($CODENAME)
deb http://deb.debian.org/debian/ $CODENAME main contrib non-free
deb http://deb.debian.org/debian/ $CODENAME-updates main contrib non-free
deb http://deb.debian.org/debian/ $CODENAME-backports main contrib non-free
deb http://security.debian.org/debian-security $CODENAME-security main contrib non-free
EOF
        sudo apt update && echo -e "${GREEN}已切换到官方源${NC}" && return 0
        
    elif [[ $DISTRO == "centos" ]]; then
        sudo tee /etc/yum.repos.d/CentOS-Base.repo << EOF
[base]
name=CentOS-\$releasever - Base
baseurl=http://mirror.centos.org/centos/\$releasever/os/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[updates]
name=CentOS-\$releasever - Updates
baseurl=http://mirror.centos.org/centos/\$releasever/updates/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[extras]
name=CentOS-\$releasever - Extras
baseurl=http://mirror.centos.org/centos/\$releasever/extras/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever
EOF
        sudo yum clean all && sudo yum makecache && echo -e "${GREEN}已切换到官方源${NC}" && return 0
        
    elif [[ $DISTRO == "fedora" ]]; then
        # Fedora 默认使用官方源，这里只是清理缓存
        sudo dnf clean all && sudo dnf makecache && echo -e "${GREEN}已切换到官方源${NC}" && return 0
        
    elif [[ $DISTRO == "rhel" ]]; then
        echo -e "${YELLOW}Red Hat Enterprise Linux 已使用官方订阅源${NC}"
        return 0
    fi
    
    echo -e "${RED}切换到官方源失败${NC}"
    return 1
}

# 安装桌面环境
install_desktop() {
    if [ "$HAS_DESKTOP" = true ]; then
        echo -e "${YELLOW}已检测到桌面环境，无需安装${NC}"
        return 0
    fi
    
    echo -e "${BLUE}正在安装桌面环境...${NC}"
    
    if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
        # 安装GNOME桌面
        sudo apt update && sudo apt install -y ubuntu-desktop || {
            handle_error "安装桌面环境失败"
            return $?
        }
        
    elif [[ $DISTRO == "centos" ]]; then
        # 安装GNOME桌面
        sudo yum groupinstall -y "GNOME Desktop" "Graphical Administration Tools" || {
            handle_error "安装桌面环境失败"
            return $?
        }
        # 设置默认启动为图形界面
        sudo systemctl set-default graphical.target
        
    elif [[ $DISTRO == "fedora" ]]; then
        # 安装GNOME桌面
        sudo dnf groupinstall -y "Fedora Workstation" || {
            handle_error "安装桌面环境失败"
            return $?
        }
        
    elif [[ $DISTRO == "rhel" ]]; then
        # 安装GNOME桌面
        sudo yum groupinstall -y "Server with GUI" || {
            handle_error "安装桌面环境失败"
            return $?
        }
        # 设置默认启动为图形界面
        sudo systemctl set-default graphical.target
    fi
    
    echo -e "${GREEN}桌面环境安装完成，建议重启系统${NC}"
    HAS_DESKTOP=true
    return 0
}

# 安装软件
install_software() {
    echo -e "${BLUE}正在安装软件...${NC}"
    
    # 如果没有桌面环境，先安装
    if [ "$HAS_DESKTOP" = false ]; then
        install_desktop || {
            echo -e "${RED}无法安装桌面环境，软件安装可能无法完成${NC}"
            return 1
        }
    fi
    
    # 根据不同发行版安装软件
    if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
        # 更新软件源
        sudo apt update
        
        # 浏览器
        install_deb_package "firefox" "Firefox浏览器"
        install_deb_package "chromium" "Chromium浏览器"
        
        # 办公套件
        install_deb_package "libreoffice" "LibreOffice办公套件"
        install_deb_package "onlyoffice-desktopeditors" "OnlyOffice办公套件"
        
        # 媒体工具
        install_deb_package "vlc" "VLC媒体播放器"
        install_deb_package "audacity" "Audacity音频编辑"
        install_deb_package "smplayer" "SMPlayer视频播放器"
        
        # 图像处理
        install_deb_package "gimp" "GIMP图像编辑"
        install_deb_package "inkscape" "Inkscape矢量图形编辑"
        
        # 开发工具
        install_vs_code_deb
        install_deb_package "gcc" "GCC编译器"
        install_deb_package "g++" "G++编译器"
        install_deb_package "git" "Git版本控制"
        install_deb_package "vim" "Vim文本编辑器"
        install_deb_package "vim-gtk3" "增强版Vim编辑器"
        install_docker_deb
        
        # 系统工具
        install_deb_package "htop" "htop系统监控"
        install_deb_package "glances" "glances系统监控"
        install_deb_package "gparted" "GParted分区工具"
        
        # 额外软件
        install_deb_package "terminator" "Terminator终端"
        install_deb_package "filezilla" "FileZilla FTP客户端"
        install_deb_package "keepassxc" "KeePassXC密码管理"
        install_deb_package "flameshot" "Flameshot截图工具"
        install_deb_package "neofetch" "系统信息展示工具"
        
    elif [[ $DISTRO == "centos" ]]; then
        # 浏览器
        install_rpm_package "firefox" "Firefox浏览器"
        install_rpm_package "chromium" "Chromium浏览器"
        
        # 办公套件
        install_rpm_package "libreoffice" "LibreOffice办公套件"
        install_onlyoffice_rpm
        
        # 媒体工具
        install_rpm_package "vlc" "VLC媒体播放器"
        install_rpm_package "audacity" "Audacity音频编辑"
        install_rpm_package "smplayer" "SMPlayer视频播放器"
        
        # 图像处理
        install_rpm_package "gimp" "GIMP图像编辑"
        install_rpm_package "inkscape" "Inkscape矢量图形编辑"
        
        # 开发工具
        install_vs_code_rpm
        install_rpm_package "gcc" "GCC编译器"
        install_rpm_package "gcc-c++" "G++编译器"
        install_rpm_package "git" "Git版本控制"
        install_rpm_package "vim" "Vim文本编辑器"
        install_rpm_package "vim-enhanced" "增强版Vim编辑器"
        install_docker_rpm
        
        # 系统工具
        install_rpm_package "htop" "htop系统监控"
        install_rpm_package "glances" "glances系统监控"
        install_rpm_package "gparted" "GParted分区工具"
        
        # 额外软件
        install_rpm_package "terminator" "Terminator终端"
        install_rpm_package "filezilla" "FileZilla FTP客户端"
        install_rpm_package "keepassxc" "KeePassXC密码管理"
        install_rpm_package "flameshot" "Flameshot截图工具"
        install_rpm_package "neofetch" "系统信息展示工具"
        
    elif [[ $DISTRO == "fedora" ]]; then
        # 浏览器
        install_rpm_package "firefox" "Firefox浏览器"
        install_rpm_package "chromium" "Chromium浏览器"
        
        # 办公套件
        install_rpm_package "libreoffice" "LibreOffice办公套件"
        install_onlyoffice_rpm
        
        # 媒体工具
        install_rpm_package "vlc" "VLC媒体播放器"
        install_rpm_package "audacity" "Audacity音频编辑"
        install_rpm_package "smplayer" "SMPlayer视频播放器"
        
        # 图像处理
        install_rpm_package "gimp" "GIMP图像编辑"
        install_rpm_package "inkscape" "Inkscape矢量图形编辑"
        
        # 开发工具
        install_vs_code_rpm
        install_rpm_package "gcc" "GCC编译器"
        install_rpm_package "gcc-c++" "G++编译器"
        install_rpm_package "git" "Git版本控制"
        install_rpm_package "vim" "Vim文本编辑器"
        install_rpm_package "vim-enhanced" "增强版Vim编辑器"
        install_docker_rpm
        
        # 系统工具
        install_rpm_package "htop" "htop系统监控"
        install_rpm_package "glances" "glances系统监控"
        install_rpm_package "gparted" "GParted分区工具"
        
        # 额外软件
        install_rpm_package "terminator" "Terminator终端"
        install_rpm_package "filezilla" "FileZilla FTP客户端"
        install_rpm_package "keepassxc" "KeePassXC密码管理"
        install_rpm_package "flameshot" "Flameshot截图工具"
        install_rpm_package "neofetch" "系统信息展示工具"
        
    elif [[ $DISTRO == "rhel" ]]; then
        echo -e "${YELLOW}Red Hat Enterprise Linux 上的软件安装可能需要订阅${NC}"
        
        # 浏览器
        install_rpm_package "firefox" "Firefox浏览器"
        install_chromium_rhel
        
        # 办公套件
        install_rpm_package "libreoffice" "LibreOffice办公套件"
        install_onlyoffice_rpm
        
        # 媒体工具
        install_rpm_package "vlc" "VLC媒体播放器"
        install_rpm_package "audacity" "Audacity音频编辑"
        install_rpm_package "smplayer" "SMPlayer视频播放器"
        
        # 图像处理
        install_rpm_package "gimp" "GIMP图像编辑"
        install_rpm_package "inkscape" "Inkscape矢量图形编辑"
        
        # 开发工具
        install_vs_code_rpm
        install_rpm_package "gcc" "GCC编译器"
        install_rpm_package "gcc-c++" "G++编译器"
        install_rpm_package "git" "Git版本控制"
        install_rpm_package "vim" "Vim文本编辑器"
        install_rpm_package "vim-enhanced" "增强版Vim编辑器"
        install_docker_rpm
        
        # 系统工具
        install_rpm_package "htop" "htop系统监控"
        install_rpm_package "glances" "glances系统监控"
        install_rpm_package "gparted" "GParted分区工具"
        
        # 额外软件
        install_rpm_package "terminator" "Terminator终端"
        install_rpm_package "filezilla" "FileZilla FTP客户端"
        install_rpm_package "keepassxc" "KeePassXC密码管理"
        install_rpm_package "flameshot" "Flameshot截图工具"
        install_rpm_package "neofetch" "系统信息展示工具"
    fi
    
    echo -e "${GREEN}软件安装完成${NC}"
    return 0
}

# 安装Debian/Ubuntu软件包
install_deb_package() {
    local package=$1
    local name=$2
    
    echo -e "${BLUE}正在安装 $name...${NC}"
    if ! sudo apt install -y $package; then
        handle_error "$name 安装失败"
        return $?
    fi
    echo -e "${GREEN}$name 安装完成${NC}"
    return 0
}

# 安装RPM软件包
install_rpm_package() {
    local package=$1
    local name=$2
    
    echo -e "${BLUE}正在安装 $name...${NC}"
    if [[ $DISTRO == "fedora" ]]; then
        if ! sudo dnf install -y $package; then
            handle_error "$name 安装失败"
            return $?
        fi
    else
        if ! sudo yum install -y $package; then
            handle_error "$name 安装失败"
            return $?
        fi
    fi
    echo -e "${GREEN}$name 安装完成${NC}"
    return 0
}

# 安装VS Code (Debian/Ubuntu)
install_vs_code_deb() {
    echo -e "${BLUE}正在安装 VS Code...${NC}"
    
    # 导入微软GPG密钥
    wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > packages.microsoft.gpg
    sudo install -o root -g root -m 644 packages.microsoft.gpg /etc/apt/trusted.gpg.d/
    rm -f packages.microsoft.gpg
    
    # 添加VS Code源
    echo "deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/repos/code stable main" | sudo tee /etc/apt/sources.list.d/vscode.list > /dev/null
    
    # 安装VS Code
    sudo apt update
    if ! sudo apt install -y code; then
        handle_error "VS Code 安装失败"
        return $?
    fi
    
    echo -e "${GREEN}VS Code 安装完成${NC}"
    return 0
}

# 安装VS Code (RPM)
install_vs_code_rpm() {
    echo -e "${BLUE}正在安装 VS Code...${NC}"
    
    # 下载并安装VS Code
    local vscode_rpm="code-1.74.0-1671278221.el7.x86_64.rpm"
    wget -q https://packages.microsoft.com/yumrepos/vscode/$vscode_rpm
    
    if [[ $DISTRO == "fedora" ]]; then
        if ! sudo dnf install -y ./$vscode_rpm; then
            handle_error "VS Code 安装失败"
            rm -f $vscode_rpm
            return $?
        fi
    else
        if ! sudo yum install -y ./$vscode_rpm; then
            handle_error "VS Code 安装失败"
            rm -f $vscode_rpm
            return $?
        fi
    fi
    
    rm -f $vscode_rpm
    echo -e "${GREEN}VS Code 安装完成${NC}"
    return 0
}

# 安装Docker (Debian/Ubuntu)
install_docker_deb() {
    echo -e "${BLUE}正在安装 Docker...${NC}"
    
    # 安装依赖
    sudo apt update
    sudo apt install -y apt-transport-https ca-certificates curl software-properties-common
    
    # 导入Docker GPG密钥
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
    
    # 添加Docker源
    sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
    
    # 安装Docker
    sudo apt update
    if ! sudo apt install -y docker-ce docker-ce-cli containerd.io; then
        handle_error "Docker 安装失败"
        return $?
    fi
    
    # 将当前用户添加到docker组
    sudo usermod -aG docker $USER
    echo -e "${YELLOW}Docker 安装完成，用户已添加到docker组，需重新登录生效${NC}"
    return 0
}

# 安装Docker (RPM)
install_docker_rpm() {
    echo -e "${BLUE}正在安装 Docker...${NC}"
    
    # 安装依赖
    if [[ $DISTRO == "fedora" ]]; then
        sudo dnf install -y dnf-plugins-core
    else
        sudo yum install -y yum-utils
    fi
    
    # 添加Docker源
    sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
    
    # 安装Docker
    if [[ $DISTRO == "fedora" ]]; then
        if ! sudo dnf install -y docker-ce docker-ce-cli containerd.io; then
            handle_error "Docker 安装失败"
            return $?
        fi
    else
        if ! sudo yum install -y docker-ce docker-ce-cli containerd.io; then
            handle_error "Docker 安装失败"
            return $?
        fi
    fi
    
    # 启动Docker服务
    sudo systemctl start docker
    sudo systemctl enable docker
    
    # 将当前用户添加到docker组
    sudo usermod -aG docker $USER
    echo -e "${YELLOW}Docker 安装完成，用户已添加到docker组，需重新登录生效${NC}"
    return 0
}

# 在RHEL上安装Chromium
install_chromium_rhel() {
    echo -e "${BLUE}正在安装 Chromium浏览器...${NC}"
    
    # 添加EPEL源
    sudo yum install -y epel-release
    
    # 安装Chromium
    if ! sudo yum install -y chromium; then
        handle_error "Chromium浏览器 安装失败"
        return $?
    fi
    
    echo -e "${GREEN}Chromium浏览器 安装完成${NC}"
    return 0
}

# 安装OnlyOffice (RPM)
install_onlyoffice_rpm() {
    echo -e "${BLUE}正在安装 OnlyOffice办公套件...${NC}"
    
    # 下载最新的OnlyOffice RPM包
    local onlyoffice_url="https://github.com/ONLYOFFICE/DesktopEditors/releases/download/v7.2.0/onlyoffice-desktopeditors-7.2.0.x86_64.rpm"
    wget -q $onlyoffice_url -O onlyoffice.rpm
    
    # 安装
    if [[ $DISTRO == "fedora" ]]; then
        if ! sudo dnf install -y ./onlyoffice.rpm; then
            handle_error "OnlyOffice办公套件 安装失败"
            rm -f onlyoffice.rpm
            return $?
        fi
    else
        if ! sudo yum install -y ./onlyoffice.rpm; then
            handle_error "OnlyOffice办公套件 安装失败"
            rm -f onlyoffice.rpm
            return $?
        fi
    fi
    
    rm -f onlyoffice.rpm
    echo -e "${GREEN}OnlyOffice办公套件 安装完成${NC}"
    return 0
}

# 系统优化菜单
optimization_menu() {
    while true; do
        clear
        echo -e "${BLUE}=============================================${NC}"
        echo -e "${CYAN}               系统优化菜单                   ${NC}"
        echo -e "${BLUE}=============================================${NC}"
        echo -e "1. 基础系统优化（适合所有用户）"
        echo -e "2. 性能优化（提升系统响应速度）"
        echo -e "3. 电源管理优化（延长笔记本电池寿命）"
        echo -e "4. 网络优化（针对国内网络环境）"
        echo -e "5. 桌面环境美化（UI优化）"
        echo -e "6. 一键全面优化（执行以上所有优化）"
        echo -e "0. 返回主菜单"
        echo -e "${BLUE}=============================================${NC}"
        read -p "请选择操作 [0-6]: " choice

        case $choice in
            1) basic_optimization && wait_for_enter ;;
            2) performance_optimization && wait_for_enter ;;
            3) power_optimization && wait_for_enter ;;
            4) network_optimization && wait_for_enter ;;
            5) desktop_optimization && wait_for_enter ;;
            6) 
                basic_optimization
                performance_optimization
                power_optimization
                network_optimization
                desktop_optimization
                echo -e "${GREEN}全面优化完成${NC}"
                wait_for_enter
                ;;
            0) break ;;
            *) 
                echo -e "${RED}无效选择，请重试${NC}"
                wait_for_enter
                ;;
        esac
    done
}

# 基础系统优化
basic_optimization() {
    echo -e "${BLUE}正在进行基础系统优化...${NC}"
    
    # 更新系统
    echo -e "${BLUE}更新系统...${NC}"
    if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
        sudo apt update && sudo apt upgrade -y && sudo apt autoremove -y
    else
        if [[ $DISTRO == "fedora" ]]; then
            sudo dnf update -y && sudo dnf autoremove -y
        else
            sudo yum update -y && sudo yum autoremove -y
        fi
    fi
    
    # 配置时区为上海
    echo -e "${BLUE}设置时区为上海...${NC}"
    sudo timedatectl set-timezone Asia/Shanghai
    
    # 启用NTP时间同步
    echo -e "${BLUE}启用时间同步...${NC}"
    sudo timedatectl set-ntp true
    
    # 配置中文支持
    echo -e "${BLUE}配置中文支持...${NC}"
    if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
        sudo apt install -y language-pack-zh-hans
    else
        if [[ $DISTRO == "fedora" ]]; then
            sudo dnf install -y langpacks-zh_CN
        else
            sudo yum install -y langpacks-zh_CN
        fi
    fi
    
    echo -e "${GREEN}基础系统优化完成${NC}"
    return 0
}

# 性能优化
performance_optimization() {
    echo -e "${BLUE}正在进行性能优化...${NC}"
    
    # 安装预加载服务，加速常用程序启动
    echo -e "${BLUE}安装预加载服务...${NC}"
    if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
        sudo apt install -y preload
        sudo systemctl enable preload
        sudo systemctl start preload
    else
        echo -e "${YELLOW}预加载服务在当前系统不支持，跳过此步骤${NC}"
    fi
    
    # 调整Swappiness
    echo -e "${BLUE}调整内存交换策略...${NC}"
    if ! grep -q "vm.swappiness=10" /etc/sysctl.conf; then
        echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.conf
        sudo sysctl -p
    fi
    
    # 启用TRIM（针对SSD）
    echo -e "${BLUE}启用SSD优化...${NC}"
    if [ -f /sys/block/sda/queue/rotational ] && [ $(cat /sys/block/sda/queue/rotational) -eq 0 ]; then
        if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
            sudo systemctl enable fstrim.timer
            sudo systemctl start fstrim.timer
        else
            sudo systemctl enable fstrim.timer
            sudo systemctl start fstrim.timer
        fi
    else
        echo -e "${YELLOW}未检测到SSD，跳过TRIM设置${NC}"
    fi
    
    echo -e "${GREEN}性能优化完成${NC}"
    return 0
}

# 电源管理优化
power_optimization() {
    echo -e "${BLUE}正在进行电源管理优化...${NC}"
    
    # 安装TLP电源管理工具
    echo -e "${BLUE}安装电源管理工具...${NC}"
    if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
        sudo apt install -y tlp tlp-rdw
        sudo systemctl enable tlp
        sudo systemctl start tlp
    else
        if [[ $DISTRO == "fedora" ]]; then
            sudo dnf install -y tlp tlp-rdw
        else
            sudo yum install -y tlp tlp-rdw
        fi
        sudo systemctl enable tlp
        sudo systemctl start tlp
    fi
    
    echo -e "${GREEN}电源管理优化完成${NC}"
    return 0
}

# 网络优化
network_optimization() {
    echo -e "${BLUE}正在进行网络优化...${NC}"
    
    # 安装网络加速工具
    echo -e "${BLUE}安装网络工具...${NC}"
    if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
        sudo apt install -y net-tools dnsutils
    else
        if [[ $DISTRO == "fedora" ]]; then
            sudo dnf install -y net-tools bind-utils
        else
            sudo yum install -y net-tools bind-utils
        fi
    fi
    
    # 配置国内DNS
    echo -e "${BLUE}配置国内DNS服务器...${NC}"
    if [ -f /etc/resolv.conf ]; then
        # 备份当前resolv.conf
        sudo cp /etc/resolv.conf /etc/resolv.conf.bak
        
        # 设置阿里云和114 DNS
        echo "nameserver 223.5.5.5" | sudo tee /etc/resolv.conf > /dev/null
        echo "nameserver 114.114.114.114" | sudo tee -a /etc/resolv.conf > /dev/null
    fi
    
    echo -e "${GREEN}网络优化完成${NC}"
    return 0
}

# 桌面环境美化（UI优化）
desktop_optimization() {
    echo -e "${BLUE}正在进行桌面环境美化...${NC}"
    
    if [ "$HAS_DESKTOP" = false ]; then
        echo -e "${YELLOW}未检测到桌面环境，先安装桌面环境${NC}"
        install_desktop || return 1
    fi
    
    # 安装主题和图标
    echo -e "${BLUE}安装主题和图标...${NC}"
    if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
        # 主题包
        sudo apt install -y numix-gtk-theme numix-icon-theme-circle
        sudo apt install -y arc-theme adapta-gtk-theme
        sudo apt install -y papirus-icon-theme
        sudo apt install -y flat-remix-gnome flat-remix
        # 桌面工具
        sudo apt install -y gnome-tweak-tool gnome-shell-extensions
        sudo apt install -y chrome-gnome-shell
        # 应用启动器
        sudo apt install -y ulauncher
        # 壁纸
        sudo apt install -y variety
        # 字体
        sudo apt install -y fonts-wqy-zenhei fonts-wqy-microhei
        sudo apt install -y fonts-noto fonts-noto-color-emoji
        sudo apt install -y fonts-hack fonts-fira-code
        
    elif [[ $DISTRO == "fedora" ]]; then
        # 主题包
        sudo dnf install -y numix-gtk-theme numix-icon-theme-circle
        sudo dnf install -y arc-theme adapta-gtk-theme
        sudo dnf install -y papirus-icon-theme
        # 桌面工具
        sudo dnf install -y gnome-tweak-tool gnome-shell-extensions
        sudo dnf install -y chrome-gnome-shell
        # 应用启动器
        sudo dnf install -y ulauncher
        # 壁纸
        sudo dnf install -y variety
        # 字体
        sudo dnf install -y wqy-zenhei-fonts wqy-microhei-fonts
        sudo dnf install -y google-noto-sans-fonts google-noto-emoji-fonts
        sudo dnf install -y hack-fonts fira-code-fonts
        
    else
        # CentOS/RHEL 系统的美化
        echo -e "${BLUE}安装基础美化工具...${NC}"
        sudo yum install -y gnome-tweak-tool
        # 字体
        sudo yum install -y wqy-zenhei-fonts wqy-microhei-fonts
        echo -e "${YELLOW}部分主题在当前系统可能不支持，已安装基础美化组件${NC}"
    fi
    
    # 配置GNOME扩展
    echo -e "${BLUE}配置GNOME扩展...${NC}"
    if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" || $DISTRO == "fedora" ]]; then
        # 安装用户主题扩展
        if ! [ -d "$HOME/.local/share/gnome-shell/extensions/user-theme@gnome-shell-extensions.gcampax.github.com" ]; then
            mkdir -p "$HOME/.local/share/gnome-shell/extensions"
            wget -q https://extensions.gnome.org/extension-data/user-themegcampax.github.com.v40.shell-extension.zip -O user-theme.zip
            unzip -q user-theme.zip -d "$HOME/.local/share/gnome-shell/extensions/user-theme@gnome-shell-extensions.gcampax.github.com"
            rm -f user-theme.zip
        fi
        
        # 启用扩展
        gnome-extensions enable user-theme@gnome-shell-extensions.gcampax.github.com
        echo -e "${GREEN}GNOME扩展配置完成${NC}"
    fi
    
    # 配置默认主题
    echo -e "${BLUE}应用推荐主题设置...${NC}"
    gsettings set org.gnome.desktop.interface gtk-theme "Arc-Dark"
    gsettings set org.gnome.desktop.interface icon-theme "Papirus"
    gsettings set org.gnome.shell.extensions.user-theme name "Arc-Dark"
    gsettings set org.gnome.desktop.background picture-uri ''
    gsettings set org.gnome.desktop.background primary-color '#2d3436'
    
    echo -e "${GREEN}桌面环境美化完成${NC}"
    echo -e "${YELLOW}提示：可以通过GNOME Tweaks工具进一步自定义您的桌面${NC}"
    return 0
}

# 等待用户按回车
wait_for_enter() {
    read -p "按回车键继续..." enter
}

# 主菜单
main_menu() {
    while true; do
        clear
        echo -e "${BLUE}=============================================${NC}"
        echo -e "${CYAN}           FastLinux v0.5 配置工具           ${NC}"
        echo -e "${BLUE}=============================================${NC}"
        echo -e "当前系统: ${YELLOW}$DISTRO $RELEASE $CODENAME${NC}"
        echo -e "桌面环境: ${YELLOW}$(if [ "$HAS_DESKTOP" = true ]; then echo "已安装"; else echo "未安装"; fi)${NC}"
        echo -e "1. 源管理（更换软件源）"
        echo -e "2. 软件安装（安装常用软件）"
        echo -e "3. 系统优化（包括UI美化）"
        echo -e "4. 安装桌面环境（单独安装）"
        echo -e "5. 重新检测系统"
        echo -e "0. 退出程序"
        echo -e "${BLUE}=============================================${NC}"
        read -p "请选择操作 [0-5]: " choice

        case $choice in
            1) source_menu ;;
            2) install_software && wait_for_enter ;;
            3) optimization_menu ;;
            4) install_desktop && wait_for_enter ;;
            5) detect_system && wait_for_enter ;;
            0) 
                echo -e "${GREEN}感谢使用 FastLinux v0.5，再见！${NC}"
                exit 0 
                ;;
            *) 
                echo -e "${RED}无效选择，请重试${NC}"
                wait_for_enter
                ;;
        esac
    done
}

# 主程序入口
main() {
    # 检查是否以root权限运行
    if [ "$(id -u)" -ne 0 ]; then
        echo -e "${YELLOW}警告：建议以root权限运行此脚本以获得完整功能${NC}"
        read -p "是否继续以当前用户运行？(y/n): " cont
        if [ "$cont" != "y" ] && [ "$cont" != "Y" ]; then
            exit 0
        fi
    fi

    # 显示用户须知
    show_user_agreement

    # 检测系统
    if ! detect_system; then
        echo -e "${RED}系统检测失败，无法继续${NC}"
        exit 1
    fi

    # 显示主菜单
    main_menu
}

# 启动主程序
main
